package com.easy.activiti;

/**
 * @author zhouchuang
 * 2024-11-05 13:57:32
 * 设置全局监听
 */

import com.easy.activiti.listener.*;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

@Configuration
@AutoConfigureAfter(
        name = {"org.activiti.spring.boot.ProcessEngineAutoConfiguration"}
)
public class ProcessEngineAutoConfigurationEnhance implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringProcessEngineConfiguration bean = applicationContext.getBean(SpringProcessEngineConfiguration.class);

        //设置全局监听器
        GlobalEventListener globalEventListener = new GlobalEventListener();
        globalEventListener.setHandlers(new HashMap<ActivitiEventType, EventHandler>() {{
            put(ActivitiEventType.TASK_CREATED, new TaskCreateListener());
            put(ActivitiEventType.TASK_COMPLETED, new TaskCompleteListener());
            put(ActivitiEventType.TASK_ASSIGNED, new TaskAssignedListener());
            put(ActivitiEventType.PROCESS_COMPLETED, new ProcessCompleteListener());
            put(ActivitiEventType.PROCESS_STARTED, new ProcessStartedListener());
        }});
        if(bean.getEventDispatcher() != null){
            bean.getEventDispatcher().addEventListener(globalEventListener);
        }else{
            List<ActivitiEventListener> eventListeners = Optional.ofNullable(bean.getEventListeners()).orElse(new ArrayList<>());
            eventListeners.add(globalEventListener);
            bean.setEventListeners(eventListeners);
        }
    }


    @Bean
    public FilterRegistrationBean<RestoreJsessionIdCookieFilter> globalFilter() {
        FilterRegistrationBean<RestoreJsessionIdCookieFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new RestoreJsessionIdCookieFilter());
        registrationBean.addUrlPatterns("/*"); // 设置过滤器的URL模式
        registrationBean.setOrder(Integer.MIN_VALUE);
        return registrationBean;
    }
}
